//导入包
const Router = require('koa-router');//koa的路由，视频里要配置的
const md5 = require('md5');//密码加密
const Moudles = require('../models');//sequelize-cli 连接数据库
const Sequelize = require('sequelize');//sequelize 数据库的增删改查
const moment = require('moment');//日期转换
const router = new Router();//建立新的路由
const Op = Sequelize.Op;//数据库的and,or...都在里面
const fs = require('fs');//操作文件的

//随便建立一个测试的，这个是get
router.get('/', async ctx => {
  let relyname = await Moudles.user.findByPk(14)//查找user表Id是14的
  ctx.body = relyname;//返回数据
});

//查询全部分类
router.get('/admin/category', async ctx => {

  let data = await Moudles.category.findAll();
  ctx.body = data;

});

//前台登录
router.get('/admin/login', async ctx => {
  let username = ctx.query.username;
  let password = ctx.query.password;
  let data = await Moudles.user.findOne({
    where: {
      username
    }
  });
  if (data === null) {
    return ctx.body = {
      code: 1,
      message: '用户名不存在'
    }
  }
  if (data.password !== md5(password)) {
    return ctx.body = {
      code: 2,
      message: '密码输入错误'
    }
  }
  if (data.disable === true) {
    return ctx.body = {
      code: 3,
      message: '非法登录'
    }
  }
  return ctx.body = {
    code: 0,
    message: '登录成功',
    data: {
      id: data.id
    }
  }
})

//post请求 添加分类
router.post('/admin/category/add', async ctx => {

  let pid = ctx.request.body.pid || 0;
  let name = ctx.request.body.name || '';

  if (name == '') {
    return ctx.body = {
      code: 1,
      message: '分类名称不能为空'
    }
  }

  let rt = await Moudles.category.findOne({
    where: {
      name
    }
  });

  if (rt != null) {
    return ctx.body = {
      code: 2,
      message: '分类名称已存在'
    }
  }

  let newcategory = await Moudles.category.build({
    pid,
    name
  }).save();

  ctx.body = {
    code: 0,
    data: newcategory
  }

});

//删除分类
router.post('/admin/category/remove', async ctx => {

  let id = ctx.request.body.id || 0;

  let rt = await Moudles.category.findOne({
    where: {
      id
    }
  });

  if (rt == null) {
    return ctx.body = {
      code: 1,
      message: '删除分类不存在'
    }
  }

  let desid = await Moudles.category.findAll({
    attributes: ['id'],
    where: {
      pid: id
    }
  });

  let rsid = await Moudles.category.destroy({
    where: {
      id
    }
  });

  ctx.body = {
    code: 0,
    data: {
      id
    }
  }

});

//修改分类
router.post('/admin/category/updat', async ctx => {

  let id = ctx.request.body.id || 0;
  let name = ctx.request.body.name || '';

  if (name == '') {
    return ctx.body = {
      code: 1,
      message: '分类名称不能为空'
    }
  }

  let rt = await Moudles.category.findOne({
    where: {
      name
    }
  });

  if (rt != null) {
    return ctx.body = {
      code: 2,
      message: '分类名称已存在'
    }
  }

  let newcategory = await Moudles.category.update(
    {
      name
    },
    {
      where: {
        id
      }
    }
  );

  ctx.body = {
    code: 0,
    data: {
      id,
      name
    }
  }

});

//后台按条件显示用户
router.get('/admin/user', async ctx => {
  let page = ctx.query.page || 1;
  let limit = 10;
  let offset = (page - 1) * limit;
  let userdisable = ctx.query.userdisable || '';
  let data;
  if (userdisable == '') {
    data = await Moudles.user.findAndCountAll({
      limit: 10,
      offset,
      order: [
        ['disable', 'ASC'],
        ['createdAt', 'ASC'],
        ['username', 'ASC'],
      ],
      include: {
        model: Moudles.profile
      }
    });
  } else {
    data = await Moudles.user.findAndCountAll({
      limit,
      offset,
      where: {
        disable: userdisable
      },
      include: {
        model: Moudles.profile
      }
    });
  }

  let prepage = data.count;
  data = [...data.rows];
  data = data.map(item => {
    let date = item.createdAt;
    date = moment(date, 'YYYY-MM-DD HH:mm:ss').format('YYYY年MM月DD日 HH:mm:ss');
    let date2 = item.profile.birthday;
    date2 = moment(date, 'YYYY-MM-DD').format('YYYY年MM月DD日');
    let data2 = {
      id: item.id,
      username: item.username,
      password: item.password,
      disable: item.disable,
      userimg: item.userimg,
      createdAt: date,
      real_name: item.profile.real_name,
      useraddress: item.profile.useraddress,
      mobile: item.profile.mobile,
      email: item.profile.email,
      gender: item.profile.gender,
      birthday: date2,
    }
    return data2;
  });
  ctx.body = {
    prepage,
    data
  };
});

//详细用户信息
router.get('/admin/user/one', async ctx => {
  let id = ctx.query.id;
  let data = await Moudles.user.findOne({
    where: {
      id
    },
    include: {
      model: Moudles.profile,
    }
  });
  let data1 = await Moudles.favorite.findAll({
    where: {
      user_id: id
    },
    include: {
      model: Moudles.cookbook,
    }
  });
  let data2 = await Moudles.cookbook.findAll({
    where: {
      user_id: id
    },
  });
  ctx.body = {
    data: {
      user: data,
      favorite: data1,
      cookbook: data2
    }
  };
});

//添加一条用户信息
router.post('/admin/user/add', async ctx => {
  let data = ctx.request.body.data || '';
  if (data.username == '') {
    return ctx.body = {
      code: 1,
      message: '用户名为空'
    }
  }

  let rs1 = await Moudles.user.findOne({
    where: {
      username: data.username
    }
  });

  if (rs1 != null) {
    return ctx.body = {
      code: 2,
      message: '用户已存在'
    }
  }

  let rs2 = await Moudles.profile.findOne({
    where: {
      mobile: data.mobile
    }
  });

  if (rs2 != null) {
    return ctx.body = {
      code: 3,
      message: '手机号已被注册'
    }
  }

  let rs3 = await Moudles.profile.findOne({
    where: {
      email: data.email
    }
  });

  if (rs3 != null) {
    return ctx.body = {
      code: 4,
      message: '邮箱已被注册'
    }
  }

  let newuser = await Moudles.user.build({
    username: data.username,
    password: md5(data.password),
    userimg: '../assets/userimg/default.jpg'
  }).save();



  let newpofile = await Moudles.profile.build({
    real_name: data.real_name,
    userId: newuser.id,
    mobile: data.mobile,
    email: data.email,
    gender: data.gender,
    useraddress: data.useraddress,
    birthday: data.birthday
  }).save();

  let newdata = await Moudles.user.findByPk(newuser.id, {
    include: {
      model: Moudles.profile
    }
  });

  ctx.body = {
    code: 0,
    data: {
      id: newdata.id,
      username: newdata.username,
      disable: newdata.disable,
      userimg: newdata.userimg,
      createdAt: newdata.createdAt,
      real_name: newdata.profile.real_name,
      useraddress: newdata.profile.useraddress,
      mobile: newdata.profile.mobile,
      email: newdata.profile.email,
      gender: newdata.profile.gender,
      birthday: newdata.profile.birthday
    }
  }

});

//添加美食信息
router.post('/admin/food/add', async ctx => {
  let data = ctx.request.body.data || '';
  console.log(data);
  let data1 = await Moudles.category.findOne({
    where: {
      name:data.category_id
    },
  })
  data.category_id = data1.id;
  console.log(data);
  let newfood = await Moudles.cookbook.build({
    name: data.name,
    userId: data.user_id,
    categoryId: data.category_id,
    pic: data.pic,
    description: data.description,
    needTime: data.need_time,
    ingredients: data.ingredients,
    levelId: data.level_id,
    tasteId: data.taste_id,
  }).save();

  ctx.body = {
    code: 0,
    data: newfood

  }

});

//对用户封号或者解封
router.post('/admin/user/updat', async ctx => {
  let id = ctx.request.body.id || 0;

  let rs = await Moudles.user.findByPk(id);

  if (rs == null) {
    return ctx.body = {
      code: 1,
      message: '用户不存在'
    }
  }

  let data = await Moudles.user.update(
    {
      disable: !rs.get('disable')
    }, {
    where: {
      id
    }
  }
  );

  ctx.body = {
    code: 0,
    message: '修改成功'
  }

});

//按条件查看美食信息
router.get('/admin/food', async ctx => {
  let page = ctx.query.page || 1;
  let a1 = ctx.query.a1 || '';
  let a2 = ctx.query.a2 || '';
  let a3 = ctx.query.a3 || '';
  let limit = 10;
  let offset = (page - 1) * limit;
  let data;
  let where = {};
  if (a1 != '') {
    where['levelId'] = a1;
  }
  if (a2 != '') {
    where['tasteId'] = a2;
  }
  if (a3 != '') {
    where['name'] = {
      [Op.like]: '%' + a3 + '%'
    }
  }

  if (a1 == '' && a2 == '' && a3 == '') {
    data = await Moudles.cookbook.findAndCountAll({
      limit,
      offset,
      order: [
        ['categoryId', 'ASC'],
        ['user_id', 'DESC'],
        ['created_at', 'ASC']
      ],
      include: [
        { model: Moudles.user },
        { model: Moudles.category }
      ]
    });
  } else {
    data = await Moudles.cookbook.findAndCountAll({
      limit,
      offset,
      where,
      order: [
        ['categoryId', 'DESC'],
      ],
      include: [
        { model: Moudles.user },
        { model: Moudles.category }
      ]
    });
  }

  let prepage = data.count;
  let pade = 0;
  data = [...data.rows];

  data = data.filter(async item => {
    if (item.category == null) {
      pade = 1;
      await Moudles.cookbook.destroy({
        where: {
          id: item.id
        },
      })
      return item;
    }

  });

  if (pade) {
    return ctx.body = {
      code: 1,
      message: '删除多余信息'
    }
  }

  data = data.map(item => {
    let date = item.createdAt;
    date = moment(date, 'YYYY-MM-DD HH:mm:ss').format('YYYY/MM/DD HH:mm:ss');
    let data2 = {
      id: item.id,
      name: item.name,
      pic: item.pic,
      categorynaem: item.category.name,
      description: item.description,
      levelId: item.levelId,
      tasteId: item.tasteId,
      needTime: item.needTime,
      ingredients: item.ingredients,
      createdAt: date,
      username: item.user.username,
    }
    return data2;

  });

  ctx.body = {
    code: 0,
    prepage,
    data
  }
});

//美食详细信息
router.get('/admin/food/one', async ctx => {
  let id = ctx.query.id || '';
  //console.log(id);
  let data = await Moudles.cookbook.findOne({
    where: {
      id
    },
    include: [
      { model: Moudles.user },
      { model: Moudles.category },
      { model: Moudles.step }
    ]
  });
  let pinlundata = await Moudles.favorite.findAndCountAll({
    where: {
      cookbookId: id
    },
  });
  let stepdata = await Moudles.step.findAndCountAll({
    where: {
      cookbookId: id
    },
  });
  //console.log(stepdata.rows);
  let date = data.createdAt;
  date = moment(date, 'YYYY-MM-DD HH:mm:ss').format('YYYY/MM/DD HH:mm:ss');
  data = {
    id: data.id,
    name: data.name,
    pic: data.pic,
    categorynaem: data.category.name,
    description: data.description,
    levelId: data.levelId,
    tasteId: data.tasteId,
    needTime: data.needTime,
    ingredients: data.ingredients,
    createdAt: date,
    username: data.user.username,
    userimg: data.user.userimg,
    foodsc: pinlundata.count,
    step: stepdata.rows,
  }
  ctx.body = {
    code: 0,
    data
  }
});

//用户作品
router.get('/admin/food/neirong', async ctx => {
  let categoryId = ctx.query.id || '';
  let data;
  if (categoryId === '') {
    data = await Moudles.cookbook.findAndCountAll({
      include: [
        { model: Moudles.user },
        { model: Moudles.category }
      ]
    });
  } else {
    data = await Moudles.cookbook.findAndCountAll({
      where: {
        categoryId: categoryId
      },
      include: [
        { model: Moudles.user },
        { model: Moudles.category }
      ]
    });
  }


  data = [...data.rows];

  data = data.map(item => {
    let date = item.createdAt;
    date = moment(date, 'YYYY-MM-DD HH:mm:ss').format('YYYY/MM/DD HH:mm:ss');
    let data2 = {
      id: item.id,
      name: item.name,
      pic: item.pic,
    }
    return data2;

  });

  ctx.body = {
    code: 0,
    data
  }
});

//轮播图图片
router.get('/admin/food/Carousel', async ctx => {
  let num = ctx.query.num || 5;

  let data = await Moudles.cookbook.findAll({
    order: [
      ['id', 'ASC'],
    ],
    limit: num,
  });

  data = data.map(item => {
    return item.pic;
  });
  // console.log(data);

  ctx.body = {
    code: 0,
    data
  }
});

//删除美食信息
router.post('/admin/food/del', async ctx => {
  let id = ctx.request.body.id || 0;

  let rs = await Moudles.cookbook.findByPk(id);

  if (rs == null) {
    return ctx.body = {
      code: 1,
      message: '用户不存在'
    }
  }

  Moudles.cookbook.destroy({
    where: {
      id
    }
  });

  Moudles.favorite.destroy({
    where: {
      cookbook_id: id
    }
  });

  Moudles.step.destroy({
    where: {
      cookbook_id: id
    }
  });

  Moudles.comment.destroy({
    where: {
      cookbook_id: id
    }
  });

  ctx.body = {
    code: 0,
    message: '删除成功'
  }
});

//按条件查询用户收藏
router.get('/admin/favorite', async ctx => {
  let page = ctx.query.page || 1;
  let a1 = ctx.query.a1 || '';
  let a2 = ctx.query.a2 || '';
  let limit = 10;
  let offset = (page - 1) * limit;
  let data;
  let where = {};
  if (a1 != '') {
    where['cookbookId'] = a1;
  }
  if (a2 != '') {
    where['userId'] = a2;
  }
  if (a1 == '' && a2 == '') {
    data = await Moudles.favorite.findAndCountAll({
      limit,
      offset,
      order: [
        ['cookbookId', 'ASC'],
        ['userId', 'ASC'],
      ],
      include: [
        { model: Moudles.user },
        { model: Moudles.cookbook }
      ]
    });
  } else {
    data = await Moudles.favorite.findAndCountAll({
      limit,
      offset,
      where,
      order: [
        ['cookbookId', 'ASC'],
        ['userId', 'ASC'],
      ],
      include: [
        { model: Moudles.user },
        { model: Moudles.cookbook }
      ]
    });
  }
  let prepage = data.count;

  data = [...data.rows];

  data = data.map(item => {
    let date = item.createdAt;
    // console.log(123);
    date = moment(date, 'YYYY-MM-DD HH:mm:ss').format('YYYY/MM/DD HH:mm:ss');
    let data2 = {
      id: item.id,
      cookbookId: item.cookbookId,
      userId: item.userId,
      username: item.user.username,
      name: item.cookbook.name,
      createdAt: date
    }
    return data2;
  });

  ctx.body = {
    prepage,
    data: data
  }
});

//按条件查找美食步骤信息
router.get('/admin/favorite/name', async ctx => {
  let group = ctx.query.group || '';
  //console.log(group);
  let data = await Moudles.favorite.findAll({
    group,
    include: [
      { model: Moudles.user },
      { model: Moudles.cookbook }
    ]
  });
  if (group == 'cookbookId') {
    data = data.map(item => {
      let data2 = {
        id: item.id,
        selectvalue: item.cookbookId,
        label: item.cookbook.name,
      }
      return data2;
    });
  }
  if (group == 'userId') {
    data = data.map(item => {
      let data2 = {
        id: item.id,
        selectvalue: item.userId,
        label: item.user.username,
      }
      return data2;
    });
  }
  ctx.body = {
    data
  }
});

//查看收藏
router.get('/admin/favorite/look', async ctx => {
  let id = ctx.query.id || '';
  let cook_id = ctx.query.cook_id;

  let rs = await Moudles.favorite.findOne({
    where: {
      user_id: id,
      cookbook_id: cook_id,
    }
  });
  if (rs === null) {
    return ctx.body = {
      code: 1
    }
  } else {
    return ctx.body = {
      code: 0
    }
  }
});

//取消收藏
router.get('/admin/favorite/lookdel', async ctx => {
  let id = ctx.query.id || '';
  let cook_id = ctx.query.cook_id;
  let data = Moudles.favorite.destroy({
    where: {
      user_id: id,
      cookbook_id: cook_id,
    }
  })
  return ctx.body = {
    code: 1,
    message: '删除成功'
  }
});

//添加收藏
router.get('/admin/favorite/lookadd', async ctx => {
  let user_id = ctx.query.id;
  let cookbook_id = ctx.query.cook_id;

  let data = Moudles.favorite.build({
    userId: user_id,
    cookbookId: cookbook_id
  }).save();
  console.log(data);
  return ctx.body = {
    code: 1,
    message: '删除成功'
  }
});

//删除收藏
router.post('/admin/favorite/del', async ctx => {
  let id = ctx.request.body.id || 0;

  let rs = await Moudles.favorite.findByPk(id);

  if (rs == null) {
    return ctx.body = {
      code: 1,
      message: '收藏信息不存在'
    }
  }

  Moudles.favorite.destroy({
    where: {
      id
    }
  })

  ctx.body = {
    code: 0,
    message: '删除成功'
  }
});

//全部评论
router.get('/admin/comment', async ctx => {
  let page = ctx.query.page || 1;
  let limit = 4;
  let offset = (page - 1) * limit;
  let prepage = 0;
  let data = await Moudles.comment.findAndCountAll({
    limit,
    offset,
    group: 'cookbook_id',
    order: [
      ['cookbook_id', 'ASC'],
    ],
    include: [
      { model: Moudles.user },
      { model: Moudles.cookbook }
    ]
  });

  let data1 = data.count;
  data = [...data.rows];

  data = data.map((item, index) => {
    let date = item.cookbook.createdAt;
    date = moment(date, 'YYYY-MM-DD HH:mm:ss').format('YYYY/MM/DD HH:mm:ss');
    prepage += data1[index].count;
    return {
      id: item.id,
      cookbookId: item.cookbookId,
      name: item.cookbook.name,
      pic: item.cookbook.pic,
      username: item.user.username,
      cout: data1[index].count,
      createdAt: date,
    }
  });

  ctx.body = {
    prepage,
    data
  }
});

//一条美食信息评论
router.get('/admin/comment/id', async ctx => {
  let page = ctx.query.page || 1;
  let id = ctx.query.id || 0;
  let limit = 10;
  let offset = (page - 1) * limit;
  let data = await Moudles.comment.findAndCountAll({
    limit,
    offset,
    where: {
      cookbook_id: id
    },
    order: [
      ['created_at', 'ASC'],
    ],
  });
  let prepage = data.count;
  data = [...data.rows];

  let reply = data.map(item => {
    return item.replyid;
  });

  let redata = await Moudles.user.findAll({
    attributes: ['username'],
    where: {
      id: { [Op.in]: reply }
    },
  });

  data = data.map((item, index) => {
    let date = item.createdAt;
    date = moment(date, 'YYYY-MM-DD HH:mm:ss').format('YYYY/MM/DD HH:mm:ss');
    return {
      id: item.id,
      replyname: redata[index].username,
      content: item.content,
      createdAt: date,
    }
  });

  ctx.body = {
    prepage,
    data
  }
});

//删除评论
router.post('/admin/comment/id/del', async ctx => {
  let id = ctx.request.body.id || 0;

  let rs = await Moudles.comment.findByPk(id);

  if (rs == null) {
    return ctx.body = {
      code: 1,
      message: '用户不存在'
    }
  }

  Moudles.comment.destroy({
    where: {
      id
    }
  })

  ctx.body = {
    code: 0,
    message: '删除成功'
  }
});

//删除该美食的全部评论
router.post('/admin/comment/del', async ctx => {
  let id = ctx.request.body.id || 0;

  let rs = await Moudles.comment.findAll({
    where: {
      cookbook_id: id
    }
  });

  if (rs == null) {
    return ctx.body = {
      code: 1,
      message: '评论信息不存在'
    }
  }

  Moudles.comment.destroy({
    where: {
      cookbook_id: id
    }
  })

  ctx.body = {
    code: 0,
    message: '删除成功'
  }
});

//查看美食步骤
router.get('/admin/step', async ctx => {
  let page = ctx.query.page || 1;
  let limit = 4;
  let offset = (page - 1) * limit;
  let prepage = 0;
  let data = await Moudles.step.findAndCountAll({
    attributes: ['cookbook_id'],
    limit,
    offset,
    group: 'cookbook_id',
    order: [
      ['cookbook_id', 'ASC'],
    ],
  });

  data = [...data.rows];
  let data2 = [];
  data.map(item => {
    data2.push(item.dataValues.cookbook_id);
  });

  let data1 = await Moudles.cookbook.findAll({
    where: {
      id: { [Op.in]: data2 }
    },
    include: [
      { model: Moudles.user },
    ]
  });

  data = data1.map(item => {
    let date = item.createdAt;
    date = moment(date, 'YYYY-MM-DD HH:mm:ss').format('YYYY/MM/DD HH:mm:ss');
    prepage++;
    return {
      id: item.id,
      name: item.name,
      username: item.user.username,
      levelId: item.levelId,
      tasteId: item.tasteId,
      createdAt: date,
      pic: item.pic
    }
  });

  ctx.body = {
    data
  };
});

//删除该美食的全部步骤
router.post('/admin/step/del', async ctx => {
  let id = ctx.request.body.id || 0;

  let rs = await Moudles.step.findAll({
    where: {
      cookbook_id: id
    }
  });

  if (rs == null) {
    return ctx.body = {
      code: 1,
      message: '菜谱信息不存在'
    }
  }

  Moudles.step.destroy({
    where: {
      cookbook_id: id
    }
  })

  ctx.body = {
    code: 0,
    message: '删除成功'
  }
});

//查看该美食的全部步骤
router.get('/admin/step/id', async ctx => {
  let page = ctx.query.page || 1;
  let id = ctx.query.id || 0;
  let limit = 10;
  let offset = (page - 1) * limit;
  let data = await Moudles.step.findAndCountAll({
    limit,
    offset,
    where: {
      cookbook_id: id
    },
    order: [
      ['created_at', 'ASC'],
    ],
  });
  let prepage = data.count;
  data = [...data.rows];

  let i = 1;
  data = data.map((item, index) => {
    let date = item.createdAt;
    date = moment(date, 'YYYY-MM-DD HH:mm:ss').format('YYYY/MM/DD HH:mm:ss');
    return {
      stepnum: i++,
      id: item.id,
      pic: item.pic,
      description: item.description,
      createdAt: date,
    }
  });

  ctx.body = {
    prepage,
    data
  }
});

//删除该美食的步骤
router.post('/admin/step/id/del', async ctx => {
  let id = ctx.request.body.id || 0;

  let rs = await Moudles.step.findByPk(id);

  if (rs == null) {
    return ctx.body = {
      code: 1,
      message: '用户不存在'
    }
  }

  Moudles.step.destroy({
    where: {
      id
    }
  })

  ctx.body = {
    code: 0,
    message: '删除成功'
  }
});

//后台登录
router.post('/admin', async ctx => {
  let username = ctx.request.body.username.trim();
  let password = ctx.request.body.password.trim();

  if (username != 'admin') {
    return ctx.body = {
      code: 1,
      message: '输入用户名不正确'
    }
  }

  if (password != 'admin') {
    return ctx.body = {
      code: 2,
      message: '输入密码不正确'
    }
  }
  ctx.cookies.set('name', 'admin', {
    httpOnly: false
  });
  ctx.session.set = 'admin';

  ctx.body = {
    code: 0,
    message: '登录成功',
  }
});

//后台退出
router.post('/admin/exit', async ctx => {
  ctx.cookies.set('name', '', { signed: false, maxAge: 0 });
  ctx.cookies.set('name.sig', '', { signed: false, maxAge: 0 });
  ctx.body = {
    code: 0,
    message: '退出登录'
  }
});

//上传图片
router.post('/admin/upload/image', async ctx => {
  let files = ctx.request.files
  let data = fs.readFileSync(files.file.path) // 读取文件
  // fs.readFileSync(pathfile);
  console.log(files.file.path);
  console.log(files.file.name);
  // let data = files.file.path.split("\\");
  let path = 'img/cook/' + files.file.name;
  fs.writeFileSync('./public/'+path,data);
  ctx.body = {
    code: 0,
    message: path
  }

});

//暴露路由
module.exports = router;

